﻿using System;
using Microsoft.Web.Administration;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.IIS7
{
	[TaskName("createIISApplication")]
	public class CreateIisApplicationTask : BaseIisWebsiteObjectTask
	{
		[TaskAttribute("appPool", Required = false), StringValidator(AllowEmpty = false)]
		public string AppPool { get; set; }

		protected override void ChangeIisConfiguration(Site site)
		{
			if (site.Applications[VirtualPath] == null)
			{
				var application = site.Applications.Add(VirtualPath, FileSystemPath);

				application.ApplicationPoolName = !string.IsNullOrWhiteSpace(AppPool)
					? AppPool
					: site.ApplicationDefaults.ApplicationPoolName;

				LogMessage("Application [{0}] created", VirtualPath);
			}
			else
			{
				if (!ErrorIfAlreadyExists)
				{
					LogMessage("Application [{0}] already exists", VirtualPath);
				}
				else
				{
					throw new Exception(string.Format("Application [{0}] already exists", VirtualPath));
				}
			}
		}
	}
}
